/*
 * Wechat I/O Backend
 */
var config = require('../config');
var common = require('../common');
var logger = common.loggerUtil.getLogger('connect-wechat');
var wechat = require('wechat');
var superagent = require('superagent');
var u = require('util');
var Q = require('q');
var wxCfg = config.wechat_gzh;
var minimatch = require('minimatch');
var S = require('string');
var redisq = require('./redisq');
var subscriberModule = require('../models/subscriber');
var subscriberProxy = require('../proxys/subscriber-proxy');
var Subscriber = subscriberModule.Subscriber;
var redisPubsubClient = require('./redis-pubsub');

function _getWxAccessToken() {
    var defer = Q.defer();
    superagent.get(u.format('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
            wxCfg.appId, wxCfg.appSecret))
        .end(function(err, res) {
            if (err) {
                defer.reject(err);
            } else if (res.statusCode !== 200) {
                defer.reject(res);
            } else {
                // res format
                // { access_token: 'xxx',
                // expires_in: 7200 }
                defer.resolve(res.body);
            }
        });
    return defer.promise;
}

function _getWxAccessTokenFromRedis() {
    var defer = Q.defer();
    redisq.getWxAccessToken()
        .then(function(data) {
            logger.debug('getWxAccessTokenFromRedis', 'access_token is retrieved from redis.');
            if (logger.isLevelEnabled('DEBUG')) {
                redisq.getWxAccessTokenTTL()
                    .then(function(ttl) {
                        logger.debug(u.format('accessToken time to live %d seconds.', ttl));
                    }, function(err) {
                        logger.warn(err);
                    })
            }
            return data;
        }, function(err) {
            return _getWxAccessToken();
        })
        .then(function(v) {
            if (typeof v == 'object' && v.access_token && v.expires_in) {
                // retrieved from WX and save into redis
                return redisq.setWxAccessToken(v);
            } else {
                defer.resolve(v);
                return;
            }
        }, function(err) {
            // _getWxAccessToken throws an err
            defer.reject(err);
            return;
        }).then(function(result) {
            /**
             * redisq setWxAccessToken get fullfiled.
             * @param  {string} result accessToken value
             * @return {string} result accessToken value
             */
            if (result) {
                logger.debug('getWxAccessTokenFromRedis', 'accessToken is updated.');
                defer.resolve(result);
            }
        })
        .fail(function(e) {
            /**
             * redisq.setWxAccessToken throw err
             * print to logging.
             * @param  {[type]}
             * @return {[type]}
             */
            if (!(defer.isFulfilled() || defer.isRejected())) {
                logger.error(e);
                defer.reject(e);
            }
        });
    return defer.promise;
}

/**
 * get subscriber information from wx server and save it into db.
 * @param  {[type]} msg [description]
 * @return {[type]}     [description]
 */
function _createSubscriberByOpenId(msg) {
    var openId = msg.FromUserName;
    var channelId = msg.EventKey;
    console.log("Get all " + JSON.stringify(msg));
    logger.debug('_createSubscriberByOpenId', 'start to save OpenID: ' + openId);
    var defer = Q.defer();
    _getWxAccessTokenFromRedis()
        .then(function(accessToken) {
            var url = u.format('https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&&openid=%s&lang=zh_CN',
                accessToken, openId);
            logger.debug('_createSubscriberByOpenId', url);
            superagent.get(url)
                .set('Accept', 'application/json')
                .end(function(err, resp) {
                    if (err) {
                        logger.error('_createSubscriberByOpenId', err);
                        throw new Error('Can not get profile data.');
                    } else {
                        logger.debug(JSON.stringify(resp));
                        // create user account by user proxy
                        logger.debug('_createSubscriberByOpenId', JSON.stringify(resp.body));
                        var profile = resp.body;
                        var subscriber = new Subscriber();
                        subscriber.name = profile.nickname;
                        subscriber.pictureUrl = profile.headimgurl;
                        subscriber.phoneNumber = "";
                        subscriber.region = profile.city;
                        subscriber.language = profile.language;
                        subscriber.city = profile.city;
                        subscriber.openId = profile.openid;
                        if (channelId) {
                            subscriber.channelId = channelId;
                        } else {
                            subscriber.channelId = "";
                        }
                        subscriberProxy.saveSubscriber(subscriber);
                        profile.channelId = channelId;
                        redisPubsubClient.publish('wechat-event-subscriber', profile);
                        console.log("Get profile " + JSON.stringify(profile));
                    }
                });
        })
        .fail(function(err) {
            logger.error(err);
        })
        .done();

    return defer.promise;

}



function onSubscribe(msg, res) {
    res.reply([{
        title: '欢迎您关注***',
        description: '导购员' + msg.EventKey + '号为您服务',
        picurl: 'http://pic15.nipic.com/20110619/7017090_100744340130_2.jpg',
        url: 'http://'+config.hostname
    }]);
    _createSubscriberByOpenId(msg);
}

function onUnsubscribe(msg, res) {
    res.send(200);
    sendToUBX(msg);
}

function sendToUBX(msg){
    var http=require('http');
    var body = {
     
        "channel" : "Social",
        "identifiers" : [ 
        {
        "name" : "email",
        "value" : "bjyyzh@cn.ibm.com"
        }
        ],
        "events" : [
        { 
        "code" : "x1fbComment", 
        "timestamp" : "2016-12-10T22:22:22Z", 
        "attributes" : [
        {
        "name" : "eventName", 
        "value" : "Facebook Comment22", 
        "type" : "string" 
        },
        {
        "name" : "body", 
        "value" : "comment facebook22", 
        "type" : "string" 
        }, 
        {
        "name" : "sentimentScore", 
        "value" : "4", 
        "type" : "string" 
        }, 
        {
        "name" : "sentiment", 
        "value" : "negative", 
        "type" : "string" 
        }
        ]
        } 
        ]
    };

    var bodyString = JSON.stringify(body);

    var headers = {
      'Authorization': 'Bearer fc187cc3-fa9c-4681-a6c5-a6727163d826',
      'Content-Type': 'application/json'
    };


    var options = {
      path: 'https://api-pilot.ubx.ibmmarketingcloud.com/v1/event ',
      method: 'POST',
      headers: headers
    };

    var req=http.request(options,function(res){
        res.setEncoding('utf-8');

        var responseString = '';

        res.on('data', function(data) {
            responseString += data;
        });

        res.on('end', function() {
            var resultObject = JSON.parse(responseString);
            console.log('-----resBody-----',resultObject);
        });

        req.on('error', function(e) {
            // TODO: handle error.
            console.log('-----error-------',e);
        });
    });
    req.write(bodyString);
    req.end();
}

function onClick(msg, res) {
    // process menu event
    switch (msg.EventKey) {
        case 'click/foo':
            res.reply([{
                title: '',
                description: '',
                picurl: '',
                url: ''
            }]);
            break;
        default:
            logger.warn('onClick', msg);
            res.send(200);
            break;
    }
}

function onDefault(msg, res) {
    logger.warn('onDefault', msg);

    if (msg.MsgType == 'text') {
        res.reply({
            content: 'This is a text',
            type: 'text'
        });
    }

    if (msg.MsgType == 'image') {
        res.reply({
            content: 'This is a image',
            type: 'text'
        });
    }

    if (msg.MsgType == 'voice') {
        res.reply({
            content: 'This is a voice',
            type: 'text'
        });
    }

    if (msg.MsgType == 'video') {
        res.reply({
            content: 'This is a video',
            type: 'text'
        });
    }

    if (msg.MsgType == 'shortvideo') {
        res.reply({
            content: 'This is a shortvideo',
            type: 'text'
        });
    }

    if (msg.MsgType == 'location') {
        res.reply({
            content: 'This is a location',
            type: 'text'
        });
    }

    if (msg.MsgType == 'link') {
        res.reply({
            content: 'This is a link',
            type: 'text'
        });
    }
}

exports.setup = function(app, path) {
    app.use(path, wechat(config.wechat_gzh.token,
        function(req, res, next) {
            // message is located in req.weixin
            var message = req.weixin;

            switch (message.Event) {
                case 'CLICK':
                    onClick(message, res);
                    break;
                case 'subscribe':
                    onSubscribe(message, res);
                    break;
                case 'unsubscribe':
                    onUnsubscribe(message, res);
                    break;
                default:
                    onDefault(message, res);
                    break;
            }
        }));
}
